package com.wanwu.channel.notify.controller;

import com.wanwu.channel.notify.biz.TradeOrderService;
import com.wanwu.channel.notify.model.PayNotifyReq;
import com.wanwu.channel.notify.model.ResponseObject;
import com.wanwu.channel.notify.model.TradeReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 交易订单
 */
@RestController
@Slf4j
@RequestMapping("/tradeOrder")
public class TradeOrderController {


    @Resource
    private TradeOrderService tradeOrderService;

    /**
     * 更新交易状态
     */
    @PostMapping("/payNotify")
    @ResponseBody
    public ResponseObject updatePayStatus(@RequestBody PayNotifyReq payNotifyReq) throws Exception {

        ResponseObject responseObject = new ResponseObject();
        responseObject.setCode("200");
        responseObject.setMessage("成功");
        try {
            tradeOrderService.syncPayStatus(payNotifyReq);
        } catch (Exception e) {
            log.error("同步交易状态失败", e);
            responseObject.setCode("500");
            responseObject.setMessage("失败");
        }
        return responseObject;
    }

    /**
     * 更新交易状态
     */
    @PostMapping("/add")
    @ResponseBody
    public ResponseObject add(@RequestBody TradeReq tradeReq) throws Exception {

        ResponseObject responseObject = new ResponseObject();
        responseObject.setCode("200");
        responseObject.setMessage("成功");
        try {
            tradeOrderService.saveTrade(tradeReq);
        } catch (Exception e) {
            log.error("同步交易状态失败", e);
            responseObject.setCode("500");
            responseObject.setMessage("失败");
        }
        return responseObject;
    }

    /**
     * 支付回调
     */
    @PostMapping("/payNotify2")
    @ResponseBody
    public Object payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String wechatNotifyStr = getRequestString(request);
            log.info("接收到【微信支付】结果回调请求，{}", wechatNotifyStr);
            tradeOrderService.payNotify(wechatNotifyStr);
        } catch (Exception e) {
            log.error("处理微信支付结果回调失败", e);
            return bulidFaildResponse(response);
        }
        return bulidSuccessResponse(response);
    }


    private String getRequestString(HttpServletRequest request) throws IOException {
        //读取微信回调报文
        ServletInputStream instream = request.getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = instream.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, len));
        }
        instream.close();
        //获得xml报文
        String wechatNotifyStr = sb.toString();
        return wechatNotifyStr;
    }

    /**
     * 处理成功返回
     *
     * @return
     */
    private Map<String, String> bulidSuccessResponse(HttpServletResponse response) {
        Map<String, String> resMsg = new HashMap<>();
        response.setStatus(200);
        resMsg.put("code", "SUCCESS");
        resMsg.put("message", "成功");
        return resMsg;
    }

    private Map<String, String> bulidFaildResponse(HttpServletResponse response) {
        Map<String, String> resMsg = new HashMap<>();
        response.setStatus(500);
        resMsg.put("code", "FAILD");
        resMsg.put("message", "失败");
        return resMsg;
    }

}